<template>
  <div v-if="['action', 'seed-action'].includes(last.type)">{{ last.label }}</div>
  <ElSelect v-else v-model="value">
    <ElOption label="<无>" value="" />
    <ElOption v-for="(action, actionName) in actions" :label="action.label" :value="actionName" :key="actionName" />
  </ElSelect>
</template>
<script setup lang="ts">
  import { ElOption, ElSelect } from 'element-plus';
  import { computed, ref, watch } from 'vue';
  import { breadcrumbs, currentApp } from '@/views/seed-dev';
  import { ComponentType } from '@/views/types';
  import { ActionConfiguration } from '@/views/dev-types';

  const props = defineProps<{microName?: string, seedName?: string, modelValue?: string, type: ComponentType}>()
  const emits = defineEmits(['update:modelValue'])
  const last = breadcrumbs.value[breadcrumbs.value.length - 1]

  const value = ref(props.modelValue)
  watch([() => props.microName, () => props.modelValue], () => value.value = props.modelValue)
  watch(() => value.value, () => emits('update:modelValue', value.value))

  const actions = computed(() => {
    const microName = props.microName
    const seedName = props.seedName
    let actions;
    if(seedName) {
      actions = microName ? currentApp.value.seeds[seedName].actions : currentApp.value.seeds[seedName].actions
    } else {      
      actions = microName ? currentApp.value.micros[microName].actions : currentApp.value.actions
    }

    const ret: Record<string, ActionConfiguration> = {}
    if(!actions) return ret

    if(!props.type) return actions

    for(const actionName in actions) {
      const action = actions[actionName]
      if(action.type === props.type) ret[actionName] = action
    }
    return ret
  })
</script>